<?php


namespace app\admin\controller;


use app\constant\WxUserConst;
use app\helper\TokenHelper;
use app\model\AdminUserVip;
use app\model\AppWxUser;
use app\util\ReturnCode;
use app\util\Tools;
use think\Db;

class AppUser extends Base
{
    /**
     * 获取用户列表
     * @return array
     * @throws \think\exception\DbException
     */
    public function getList()
    {

        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $type = $this->request->get('type', '');
        $keywords = $this->request->get('keywords', '');
        $status = $this->request->get('status', '');
        $search_type = $this->request->get('search_type', '', 'intval');
        $obj = new AppWxUser();
        $where = [];
        if (strlen($status)) {
            $where['status'] = $status;
        }
        if (strlen($type)) {
            $where['type'] = $type;
        }
        if ($search_type) {
            switch ($search_type) {
                case 1:
                    $obj = $obj->whereLike('nickname', "%{$keywords}%");
                    break;
                case 2:
                    $obj = $obj->whereLike('username', "%{$keywords}%");
                    break;
            }
        }
        //添加站点筛选
        $obj = $obj->where($this->addTid($where));
        $listObj = $obj->order('create_time DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];

        return $this->buildSuccess([
            'list' => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    public function edit()
    {
        $postData = $this->request->post();
        unset($postData['tid']);
        if(isset($postData['password'])){
            $postData['password'] =  Tools::userMd5($postData['password']);
        }
        Db::startTrans();
        try{
            if($postData['type']==WxUserConst::TYPE_VIP){
                $vipData = ['id'=>$postData['id'],'expiration_time'=>$postData['date']];
                $vipData = $this->addTid($vipData);
                $done = (new AdminUserVip())->save($vipData);
                if(!$done){
                    throw new \Exception('更新会员日期失败');
                }
            }
            //判断是否要存帐号
            if(isset($postData['username'])){
                $userNameWhere = ['username'=>$postData['username']];
                $userNameWhere = $this->addTid($userNameWhere);
                $has = AppWxUser::get($userNameWhere);
                if($has&&$has->id!==$postData['id']){
                    throw new \Exception('用户名已经存在了');
                }
            }

            $done = AppWxUser::update($postData);
            if(!$done){
                throw new \Exception('更新失败');
            }
            Db::commit();
            //去更新用户的token（假设有的话）
            TokenHelper::updateToken($postData['id']);
            return $this->buildSuccess(null);

        }catch (\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::FAILED, '操作失败'.$e->getMessage());
        }
    }

    public function getDetail()
    {
        $uid = $this->request->get('uid');
        if(!isset($uid)){
            return $this->buildFailed(ReturnCode::INVALID, '无效的参数');
        }
        $where = ['id'=>$uid];
        $where = $this->addTid($where);
        $appUser = AppWxUser::get($where);
        if(!$appUser){
            return $this->buildFailed(ReturnCode::INVALID, '不存在的用户');
        }
        $userVip = AdminUserVip::get($uid);
        $data = $appUser->getData();
        if($userVip){
            $data['expiration_time'] = $userVip->expiration_time;
        }
        return $this->buildSuccess($data);

    }

    public function changeStatus()
    {
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        $data = [
            'id' => $id,
            'status' => $status
        ];
        $data = $this->addTid($data);
       $res = AppWxUser::update($data);
       if ($res === false) {
           return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
       } else {
           return $this->buildSuccess([]);
       }
    }


}